<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="queryParams.description" placeholder="请输入描述" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="群总数" prop="totalCount">
        <el-input v-model="queryParams.totalCount" placeholder="请输入群总数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="未使用" prop="unusedCount">
        <el-input v-model="queryParams.unusedCount" placeholder="请输入未使用" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="使用中" prop="usingCount">
        <el-input v-model="queryParams.usingCount" placeholder="请输入使用中" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="已使用" prop="usedCount">
        <el-input v-model="queryParams.usedCount" placeholder="请输入已使用" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="不存在" prop="notExistCount">
        <el-input v-model="queryParams.notExistCount" placeholder="请输入不存在" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['yunkong:group-pool:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['yunkong:group-pool:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['yunkong:group-pool:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column type="index" label="序号" align="left" prop="id" /> -->
      <el-table-column label="序号" type="index" width="55" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="群总数" align="center" prop="totalCount" />
      <el-table-column label="未使用" align="center" prop="unusedCount" />
      <el-table-column label="使用中" align="center" prop="usingCount" />
      <el-table-column label="已使用" align="center" prop="usedCount" />
      <el-table-column label="不存在" align="center" prop="notExistCount" />
      <el-table-column label="导入进度" align="center" width="220px">
        <template #default="scope">
          <div v-if="importTasks[scope.row.id]">
            <el-progress :percentage="calculateProgress(importTasks[scope.row.id])"
              :status="getImportStatus(importTasks[scope.row.id])" />
            <div class="text-xs mt-1">
              {{ getImportStatusText(importTasks[scope.row.id]) }}
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="170px" />
      <el-table-column label="操作" align="center" min-width="170px" fixed="right">
        <template #default="scope">
          <div class="flex items-center justify-center space-x-2">
            <el-button link type="primary" @click="openDetail(scope.row.id)" v-hasPermi="['yunkong:group-pool:query']">
              查看
            </el-button>
            <el-button link type="success" @click="openImport(scope.row)" v-hasPermi="['yunkong:group-pool:query']">
              导入
            </el-button>
            
            <el-dropdown>
              <el-button link type="primary">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleClear(scope.row.id, scope.row.name)"
                    v-hasPermi="['yunkong:group-pool:delete']">
                    <el-button link type="warning">清空</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item @click="openForm('update', scope.row.id)" v-hasPermi="['yunkong:group-pool:update']">
                    <el-button link type="primary">编辑</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(scope.row.id)" v-hasPermi="['yunkong:group-pool:delete']">
                    <el-button link type="danger">删除</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <GroupPoolForm ref="formRef" @success="getList" />

  <!-- 群号池子详情弹窗 -->
  <GroupPoolDetail ref="detailRef" />

  <!-- 导入群号弹窗 -->
  <ImportDialog ref="importDialogRef" @success="handleImportSuccess" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { GroupPoolApi, GroupPool } from '@/api/yunkong/grouppool'
import { ImportTaskApi, ImportTask, ImportTaskStatus } from '@/api/yunkong/importtask'
import GroupPoolForm from './GroupPoolForm.vue'
import GroupPoolDetail from './components/GroupPoolDetail.vue'
import ImportDialog from './components/ImportDialog.vue'
import { ArrowDown } from '@element-plus/icons-vue'

/** 群号池子 列表 */
defineOptions({ name: 'GroupPool' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<GroupPool[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  description: undefined,
  totalCount: undefined,
  unusedCount: undefined,
  usingCount: undefined,
  usedCount: undefined,
  notExistCount: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const detailRef = ref() // 详情弹窗
const importDialogRef = ref() // 导入弹窗
const importTasks = reactive<Record<number, ImportTask>>({}) // 导入任务记录，键为池子ID
const pollingTimers = reactive<Record<number, number>>({}) // 轮询定时器，键为任务ID

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await GroupPoolApi.getGroupPoolPage(queryParams)
    list.value = data.list
    total.value = data.total

    // 查询每个池子的最新导入任务
    await checkImportTasks()
  } finally {
    loading.value = false
  }
}

/** 检查所有池子的导入任务状态 */
const checkImportTasks = async () => {
  if (!list.value || list.value.length === 0) return

  // 遍历所有池子，查询其最新导入任务
  for (const pool of list.value) {
    try {
      const task = await ImportTaskApi.getLatestTaskByBusinessId(pool.id)
      if (task) {
        // 记录任务
        importTasks[pool.id] = task

        // 如果任务未完成，启动轮询
        if (task.status !== ImportTaskStatus.COMPLETED && task.status !== ImportTaskStatus.FAILED) {
          startPolling(task.id)
        }
      }
    } catch (error) {
      console.error(`查询池子${pool.id}的导入任务失败`, error)
    }
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 查看详情操作 */
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 打开导入弹窗 */
const openImport = (row: GroupPool) => {
  importDialogRef.value.open(row.id, row.name)
}

/** 处理导入成功 */
const handleImportSuccess = (taskId: number) => {
  // 查询任务详情
  queryImportTask(taskId)
}

/** 查询导入任务 */
const queryImportTask = async (taskId: number) => {
  try {
    const task = await ImportTaskApi.getImportTask(taskId)
    if (task) {

      // 记录任务
      importTasks[task.businessId] = task

      // 如果任务未完成，启动轮询
      if (task.status !== ImportTaskStatus.COMPLETED && task.status !== ImportTaskStatus.FAILED) {
        startPolling(taskId)
      } else {
        // 任务完成，刷新列表
        getList()
      }
    }
  } catch (error) {
    console.error('查询导入任务失败', error)
  }
}

/** 启动轮询 */
const startPolling = (taskId: number) => {
  // 清除可能存在的定时器
  if (pollingTimers[taskId]) {
    clearTimeout(pollingTimers[taskId])
  }

  // 设置新的定时器，每3秒查询一次
  pollingTimers[taskId] = window.setTimeout(async () => {
    try {
      const task = await ImportTaskApi.getImportTask(taskId)
      if (task) {
        // 更新任务状态
        importTasks[task.businessId] = task

        // 如果任务未完成，继续轮询
        if (task.status !== ImportTaskStatus.COMPLETED && task.status !== ImportTaskStatus.FAILED) {
          startPolling(taskId)
        } else {
          // 任务完成，刷新列表
          getList()
        }
      }
    } catch (error) {
      console.error('轮询导入任务失败', error)
    }
  }, 3000)
}

/** 计算进度百分比 */
const calculateProgress = (task: ImportTask) => {
  if (!task) return 0

  if (task.status === ImportTaskStatus.QUEUED) return 0
  if (task.status === ImportTaskStatus.COMPLETED) return 100

  if (task.totalCount === 0) return 0
  return Math.floor((task.processedCount / task.totalCount) * 100)
}

/** 获取导入状态 */
const getImportStatus = (task: ImportTask) => {
  if (!task) return ''

  switch (task.status) {
    case ImportTaskStatus.QUEUED:
      return 'warning'
    case ImportTaskStatus.PROCESSING:
      return ''
    case ImportTaskStatus.COMPLETED:
      return 'success'
    case ImportTaskStatus.FAILED:
      return 'exception'
    default:
      return ''
  }
}

/** 获取导入状态文本 */
const getImportStatusText = (task: ImportTask) => {
  if (!task) return ''

  switch (task.status) {
    case ImportTaskStatus.QUEUED:
      return '排队中'
    case ImportTaskStatus.PROCESSING:
      return `处理中 (${task.processedCount}/${task.totalCount})`
    case ImportTaskStatus.COMPLETED:
      return `完成 (成功:${task.successCount}, 失败:${task.failedCount}, 重复:${task.duplicateCount})`
    case ImportTaskStatus.FAILED:
      return `失败: ${task.errorMsg || '未知错误'}`
    default:
      return ''
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await GroupPoolApi.deleteGroupPool(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除群号池子 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await GroupPoolApi.deleteGroupPoolList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

/** 清空群号池 */
const handleClear = async (id: number, name: string) => {
  try {
    // 清空的二次确认
    await message.confirm(`确定要清空群号池"${name}"中的所有群号吗？此操作不可恢复！`)

    // 发起清空请求
    await GroupPoolApi.deleteGroupPoolByCondition({ poolId: id })
    message.success('清空成功')

    // 刷新列表
    await getList()
  } catch (error) {
    console.error('清空群号池失败', error)
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: GroupPool[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await GroupPoolApi.exportGroupPool(queryParams)
    download.excel(data, '群号池子.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

/** 清理定时器 */
onBeforeUnmount(() => {
  Object.values(pollingTimers).forEach(timer => {
    clearTimeout(timer)
  })
})
</script>